<script setup lang="ts">
import {CopyDocument} from "@element-plus/icons-vue";
import {ElButton, ElCard, ElMessage, ElTable, ElTableColumn} from "element-plus";
import {onUpdated, ref, watch} from "vue";
import {SoftwareQuery} from "@/type.ts";
const softwareQuery = ref<SoftwareQuery>()
const desList=ref([])
const linkNameList=ref([])

interface Props{
  list?:SoftwareQuery[]
}
const  props= defineProps<Props>()
const softwareQueryList=ref()

watch(softwareQueryList,()=>{
  const uniqueDescriptions: { [key: string]: boolean } = {};
  const uniqueLinkNames: { [key: string]: boolean } = {};
  const uniqueDescriptionObjects: { text: string; value: string }[] = [];
  const uniqueLinkNameObjects: { text: string; value: string }[] = [];

  (softwareQueryList?.value ?? []).forEach(item => {
    if (item.description && !uniqueDescriptions[item.description]) {
      uniqueDescriptions[item.description] = true;
      uniqueDescriptionObjects.push({ text: item.description, value: item.description });
    }
    if (item.linkName && !uniqueLinkNames[item.linkName]) {
      uniqueLinkNames[item.linkName] = true;
      uniqueLinkNameObjects.push({ text: item.linkName, value: item.linkName });
    }
  });
  desList.value=uniqueDescriptionObjects
  linkNameList.value=uniqueLinkNameObjects

});
onUpdated(()=>{
  softwareQueryList.value=props.list
  if (softwareQueryList.value.length !== 0) {
    // softwareQuery.value = softwareQueryList.value.pop()
    /*使用扩展运算符 ... 创建 softwareQueryList.value 的浅拷贝*/
    const newList = [...softwareQueryList.value];
    if (newList.length !== 0) {
      /*从新数组中移除最后一个元素，并返回该元素*/
      softwareQuery.value = newList.pop();
    }
  }
})

const canUseClipboardAPI = () => {
  // 检查浏览器是否支持剪贴板API
  return navigator.clipboard && typeof navigator.clipboard.writeText === 'function';
};

const filterDescription = (value: string, row: SoftwareQuery) => {
  return row.description === value
}
const filterLinkName = (value: string, row: SoftwareQuery) => {
  return row.linkName === value
}


const copyRowData = (row) => {
  const rowString = row.linkUrl
  if (canUseClipboardAPI()) {
    navigator.clipboard.writeText(rowString).then(() => {
      ElMessage.success('Copy Success');
      // 3秒后自动关闭消息
    }).catch((err) => {
      ElMessage.error(err);
    });
  } else {
    fallbackCopy(rowString)
  }

};

const fallbackCopy = (text) => {
  const textArea = document.createElement('textarea');
  textArea.value = text;
  // 避免页面滚动
  textArea.style.position = 'fixed';
  textArea.style.top = '-9999px';
  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();
  try {
    const successful = document.execCommand('copy');
    if (successful) {
      ElMessage.success('复制成功');
    } else {
      ElMessage.error('复制失败，请尝试手动复制!')
    }
  } catch (err) {
    console.error('回退复制失败:', err);
    ElMessage.error('复制失败，请尝试手动复制!')
  }
  document.body.removeChild(textArea);
};
const handleClick = (row) => {
  softwareQuery.value = row;
}
</script>

<template>
  <el-card>
    <div style="height: calc(100vh - 235px);">

      <div style="display: flex; flex-direction: column; height: 100%"
           v-if="softwareQueryList">
        <div v-if="softwareQuery" class="software-info-card">
          <el-scrollbar>
            <p v-if="softwareQuery.des" class="software-desc">{{ softwareQuery.des }}</p>
          </el-scrollbar>

        </div>

        <el-table :data="props.list" style="width: 100%;flex-grow: 1"
                  :default-sort="{ prop: 'description', order: 'descending' }"
                  @row-click="handleClick"
                  >


          <el-table-column label="软件名称" prop="aliasName" width="150px" allign="center"/>

          <el-table-column label="系统版本" prop="description" width="120px"
                           :filters="desList"
                           :filter-method="filterDescription"
                           filter-placement="bottom-end"/>
          <el-table-column label="注意事项" prop="remark" width="150px" allign="center"/>
          <el-table-column label="价格" width="100px" allign="center">
            <template #default="{ row }">
              {{ row?.minPrice }} - {{ row?.maxPrice }}
            </template>
          </el-table-column>
          <el-table-column label="下载方式" prop="linkName" width="100px" allign="center"
                           :filters="linkNameList"
                           :filter-method="filterLinkName"
                           filter-placement="bottom-end"/>
          <el-table-column label="下载链接" prop="linkUrl"/>

          <el-table-column label="操作" width="100px">
            <template #default="{ row }">
              <el-button :icon="CopyDocument" @click="copyRowData(row)" link/>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else description="There is no software selected"/>
    </div>
  </el-card>
</template>

<style scoped>

.software-info-card {
  margin-bottom: 10px;
  max-height: 160px;
  border-radius: 8px;
  border: #d1d1d1 2px dashed;
  padding: 8px;
  box-shadow: rgba(17, 17, 26, 0.05) 0 4px 16px, rgba(17, 17, 26, 0.05) 0 8px 32px;
}

.software-desc {
  text-align: start;
  margin: 0 16px;
  text-indent: 2em;
  font-size: 13px
}

</style>
